import { defineStore } from "pinia";
import { store } from "@/store";
import { ref } from "vue";
import { sendSock, createWebSocket, closeSock } from "@/utils/ws/websocket.js";

export const useLmswsStore = defineStore({
  id: "lmsws",
  state: () => ({
    serviceMsg: ref({
      type: 0,
      data: ""
    })
  }),
  actions: {
    init(wsurl) {
      createWebSocket(wsurl, this.global_callback);
    },
    global_callback(msg) {
      this.serviceMsg.value = msg;
    },
    send(sendData) {
      sendSock(JSON.stringify(sendData));
    },
    close({ isActiveClose = false }) {
      closeSock({ activeClose: isActiveClose });
    },
    closeAndRestart() {
      this.close({ isActiveClose: true });
      this.init();
    }
  }
});

export function useLmswsStoreHook() {
  return useLmswsStore(store);
}
